/* Copyright Statement:
 *
 * This software/firmware and related documentation ("MediaTek Software") are
 * protected under relevant copyright laws. The information contained herein is
 * confidential and proprietary to MediaTek Inc. and/or its licensors. Without
 * the prior written permission of MediaTek inc. and/or its licensors, any
 * reproduction, modification, use or disclosure of MediaTek Software, and
 * information contained herein, in whole or in part, shall be strictly
 * prohibited.
 *
 * MediaTek Inc. (C) 2010. All rights reserved.
 *
 * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
 * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
 * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER
 * ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL
 * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
 * NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH
 * RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
 * INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES
 * TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO.
 * RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO
 * OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK
 * SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE
 * RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
 * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S
 * ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE
 * RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE
 * MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE
 * CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
 *
 * The following software/firmware and/or related documentation ("MediaTek
 * Software") have been modified by MediaTek Inc. All revisions are subject to
 * any receiver's applicable license agreements with MediaTek Inc.
 */

package com.mediatek.datatransfer;

import java.util.ArrayList;
import java.util.List;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Outline;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.view.Window;
import com.tecno.widget.Toast;

import android.widget.ImageButton;
import android.widget.Toolbar;

import com.mediatek.datatransfer.utils.Constants;
import com.mediatek.datatransfer.utils.Constants.DialogID;
import com.mediatek.datatransfer.utils.MyLogger;
import com.mediatek.datatransfer.utils.NotifyManager;
import com.mediatek.datatransfer.utils.SDCardUtils;
import com.mediatek.datatransfer.view.CustomViewPager;
import com.mediatek.datatransfer.view.ViewPagerTabs;
import android.os.Build;

/**
 * @author mtk81330
 *
 */
public class MainActivity extends Activity {
    private static final String CLASS_TAG = MyLogger.LOG_TAG + "/MainActivity";
    private static final String STATE_TAB = "tab";
    public static final String ACTION_WHERE = "action_where";
    public static final String ACTION_BACKUP = "action_backup";
    public static final String ACTION_RESTORE = "ction_restore";
    //A meng.wu CQHSWW-726 20160503@{
    private static final int RESUME_PERMISSION_REQUEST_CODE = 104;
    //@}
    private Fragment mBackupFragment;
    private Fragment mRestoreFragment;
    MainOnSDCardStatusChangedListener mMainOnSDCardStatusChangedListener =
            new MainOnSDCardStatusChangedListener();
    private ViewPagerTabs mViewPagerTabs;
    private CustomViewPager mTabPager;
    private ArrayList<Fragment> mFragments = new ArrayList<Fragment>();
    private String[] mFragmentTitles = new String[2];
    private ImageButton mFooterButton;
    
    public static final ViewOutlineProvider OVAL_OUTLINE_PROVIDER = new ViewOutlineProvider() {
		@Override
		public void getOutline(View view, Outline outline) {
			outline.setOval(0, 0, view.getWidth(), view.getHeight());
		}
	};
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        MyLogger.logD(CLASS_TAG, "onCreate");
        //A meng.wu CQHSWW-726 20160503@{
        // if(Build.VERSION.SDK_INT >=23){
        // checkAllNeedDangerousPermission(RESUME_PERMISSION_REQUEST_CODE);
        // }
        //@}
        View view = findViewById(R.id.main_view);
        if(view == null){
        	setContentView(R.layout.main_activity);
        }
        initFragments(savedInstanceState);
        //setupActionBar(savedInstanceState);
        setupTitleBar();
        setProgressBarIndeterminateVisibility(false);
        registerSDCardListener();
        NotifyManager.getInstance(this).clearNotification();
        mFooterButton = (ImageButton)findViewById(R.id.backup_bt_backcup);
        View backFl = findViewById(R.id.backup_fl_backcup);
        if(mFooterButton != null){
        	mFooterButton.setVisibility(View.INVISIBLE);
        	//mFooterButton.setOutlineProvider(OVAL_OUTLINE_PROVIDER);
        }
        if(backFl != null){
        	backFl.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MyLogger.logD(CLASS_TAG, "onResume");
        Intent actionIntent = getIntent();
        //A meng.wu CQHSWW-726 20160503@{
        if(Build.VERSION.SDK_INT >=23){
        checkAllNeedDangerousPermission(RESUME_PERMISSION_REQUEST_CODE);
        }
        //@}
        sdCardCheck();
    }

    private void sdCardCheck() {
        if (SDCardUtils.getExternalStoragePath(this) == null) {
			//modify JBHSLS-135 zhiqiang.peng 20150514 (on)
            //Toast.makeText(this, R.string.nosdcard_notice, Toast.LENGTH_SHORT).show();
            //MainActivity.this.finish();
			showDialog(DialogID.DLG_NO_SDCARD);
			//modify JBHSLS-135 zhiqiang.peng 20150514 (off)
        } else {
            removeDialog(DialogID.DLG_NO_SDCARD);
        }
    }

    protected void onDestroy() {
        super.onDestroy();
        MyLogger.logD(CLASS_TAG, "onDestroy");
        unRegisterSDCardListener();
    }

    @Override
    protected void onPause() {
        super.onPause();
        MyLogger.logD(CLASS_TAG, "onPause");
        removeDialog(DialogID.DLG_NO_SDCARD);
    }

    protected void  onSaveInstanceState(Bundle outState) {
        //ActionBar bar = getActionBar();
        //int position = bar.getSelectedNavigationIndex();
        //outState.putInt(STATE_TAB, position);
        super.onSaveInstanceState(outState);
    }
    
    @Override
    public void onBackPressed() {
    	RestoreTabFragment rf = (RestoreTabFragment)mRestoreFragment;
    	if(rf != null && rf.getDeleteMode()){
    		rf.showDeleteMenu(false);
    		return;
    	}
    	super.onBackPressed();
    }
    
    private void initFragments(Bundle state) {
        FragmentManager fm = getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        boolean isCommit = false;
        mFragments.clear();
        if (state != null) {
            mBackupFragment = fm.findFragmentByTag(Constants.BACKUP);
            mRestoreFragment = fm.findFragmentByTag(Constants.RESTORE);
        }
        if (mBackupFragment == null) {
            mBackupFragment = new BackupTabFragment();
            ft.add(R.id.tab_pager, mBackupFragment,Constants.BACKUP);
            isCommit = true;
        }
        mFragments.add(mBackupFragment);
        mFragmentTitles[0] = getString(R.string.backup);
        if (mRestoreFragment == null) {
            mRestoreFragment = new RestoreTabFragment();
            ft.add(R.id.tab_pager, mRestoreFragment,Constants.RESTORE);
            isCommit = true;
        }
        mFragments.add(mRestoreFragment);
        mFragmentTitles[1] = getString(R.string.restore);
        if(isCommit){
        	ft.commitAllowingStateLoss();
            fm.executePendingTransactions();
        }
    }

    private void registerSDCardListener() {
        SDCardReceiver.getInstance().registerOnSDCardChangedListener(
                mMainOnSDCardStatusChangedListener);
    }

    private void unRegisterSDCardListener() {
        SDCardReceiver.getInstance().unRegisterOnSDCardChangedListener(
                mMainOnSDCardStatusChangedListener);
    }

    /**
     * @author mtk81330
     *
     */
    class MainOnSDCardStatusChangedListener implements
    SDCardReceiver.OnSDCardStatusChangedListener {

        @Override
        public void onSDCardStatusChanged(boolean mount) {
            // TODO Auto-generated method stub
            MyLogger.logD(CLASS_TAG, "onSDCardStatusChanged - " + mount);
            sdCardCheck();
        }
    }

    //rlk add meng.wu CQHSWW-726 20160503  @{
    private void checkAllNeedDangerousPermission(int requestCode) {
        List<String> mPermissionStrings = new ArrayList<String>();
        boolean mRequest = false;
        /*if(!checkAccessReadContact()) {
            mPermissionStrings.add(Manifest.permission.READ_CONTACTS);
            mRequest = true;
        }
        if(!checkAccessWriteContact()) {
            mPermissionStrings.add(Manifest.permission.WRITE_CONTACTS);
            mRequest = true;
        }*/
        if(!checkAccessReadStorage()) {
            mPermissionStrings.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            mRequest = true;
        }
        /*if(!checkAccessWriteStorage()) {
            mPermissionStrings.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            mRequest = true;
        }
        if(!checkAccessReadCalendar()) {
            mPermissionStrings.add(Manifest.permission.READ_CALENDAR);
            mRequest = true;
        }
        if(!checkAccessWriteCalendar()) {
            mPermissionStrings.add(Manifest.permission.WRITE_CALENDAR);
            mRequest = true;
        }
        if(!checkAccessReadPhoneState()) {
            mPermissionStrings.add(Manifest.permission.READ_PHONE_STATE);
            mRequest = true;
        }
        if(!checkAccessWriteCalllog()) {
            mPermissionStrings.add(Manifest.permission.WRITE_CALL_LOG);
            mRequest = true;
        }
        if(!checkAccessReadCalllog()) {
            mPermissionStrings.add(Manifest.permission.READ_CALL_LOG);
            mRequest = true;
        }
        if(!checkAccessWriteSms()) {
            mPermissionStrings.add(Manifest.permission.WRITE_SMS);
            mRequest = true;
        }
        if(!checkAccessReadSms()) {
            mPermissionStrings.add(Manifest.permission.READ_SMS);
            mRequest = true;
        }*/
        if(mRequest) {
            String[] mPermissionList = new String[mPermissionStrings.size()];
            mPermissionList = mPermissionStrings.toArray(mPermissionList);
            ActivityCompat.requestPermissions(this, mPermissionList, 
                    requestCode);
        /*}else {
            sdCardCheck();*/
        }
    }
    
    /*private boolean checkAccessReadContact() {
        return ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED;
    }
    
    private boolean checkAccessWriteContact() {
        return ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_CONTACTS) == PackageManager.PERMISSION_GRANTED;
    }*/
    
    private boolean checkAccessReadStorage() {
        return ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
    }
    
    /*private boolean checkAccessWriteStorage() {
        return ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
    }
    
    private boolean checkAccessReadCalendar() {
        return ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_CALENDAR) == PackageManager.PERMISSION_GRANTED;
    }
    
    private boolean checkAccessWriteCalendar() {
        return ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_CALENDAR) == PackageManager.PERMISSION_GRANTED;
    }
    
    private boolean checkAccessReadPhoneState() {
        return ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED;
    }
    
    private boolean checkAccessReadCalllog() {
        return ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_CALL_LOG) == PackageManager.PERMISSION_GRANTED;
    }
    
    private boolean checkAccessWriteCalllog() {
        return ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_CALL_LOG) == PackageManager.PERMISSION_GRANTED;
    }
    
    private boolean checkAccessReadSms() {
        return ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED;
    }
    
    private boolean checkAccessWriteSms() {
        return ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_SMS) == PackageManager.PERMISSION_GRANTED;
    }*/
    //@}    
    private void setupTitleBar(){
    	mTabPager = (CustomViewPager)findViewById(R.id.tab_pager);
    	mTabPager.setAdapter(new TitleBarPagerAdapter(mFragments));
    	mTabPager.setOnPageChangeListener(new TabPagerListener());
        mTabPager.setOffscreenPageLimit(1);
        mViewPagerTabs = (ViewPagerTabs) findViewById(R.id.lists_pager_header);
        mViewPagerTabs.setViewPager(mTabPager);
        setSelectRestorePage();//A LBHBLW-567 by huan.yang 20160107
    }
    
    private class TabPagerListener implements ViewPager.OnPageChangeListener {

		@Override
		public void onPageScrollStateChanged(int state) {
			mViewPagerTabs.onPageScrollStateChanged(state);
		}

		@Override
		public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
			mViewPagerTabs.onPageScrolled(position, positionOffset, positionOffsetPixels);
			RestoreTabFragment rf = (RestoreTabFragment)mRestoreFragment;
			if(rf != null && rf.getDeleteMode()){
				rf.showDeleteMenu(false);
			}
		}

		@Override
		public void onPageSelected(int position) {
            mViewPagerTabs.onPageSelected(position);
		}
    	
    }
    
    private class TitleBarPagerAdapter extends PagerAdapter {
    	
    	private final FragmentManager mFragmentManager;
        private FragmentTransaction mCurTransaction = null;
        private ArrayList<Fragment> mTFragments;
        private Fragment mCurrentPrimaryItem;
    	
        public TitleBarPagerAdapter(ArrayList<Fragment> fragments){
        	mTFragments = fragments;
        	mFragmentManager = getFragmentManager();
        }
        
    	@Override
    	public void startUpdate(ViewGroup container) {
    		super.startUpdate(container);
    	}
    	
    	@Override
        public void finishUpdate(ViewGroup container) {
            if (mCurTransaction != null) {
                mCurTransaction.commitAllowingStateLoss();
                mCurTransaction = null;
                mFragmentManager.executePendingTransactions();
            }
        }
    	
		@Override
		public int getCount() {
			return mTFragments.size();
		}

		@Override
		public void setPrimaryItem(ViewGroup container, int position,
				Object object) {
			Fragment fragment = (Fragment) object;
            if (mCurrentPrimaryItem != fragment) {
                if (mCurrentPrimaryItem != null) {
                    mCurrentPrimaryItem.setUserVisibleHint(false);
                }
                if (fragment != null) {
                    fragment.setUserVisibleHint(true);
                }
                mCurrentPrimaryItem = fragment;
            }
		}
			
		@Override
		public boolean isViewFromObject(View view, Object object) {
			return ((Fragment) object).getView() == view;
		}
    	
		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			if (mCurTransaction == null) {
                mCurTransaction = mFragmentManager.beginTransaction();
            }
            Fragment f = mTFragments.get(position);
            mCurTransaction.show(f);
            f.setUserVisibleHint(true);
            return f;
		}
		
		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			if (mCurTransaction == null) {
                mCurTransaction = mFragmentManager.beginTransaction();
            }
            mCurTransaction.hide((Fragment) object);
		}
		
		@Override
		public CharSequence getPageTitle(int position) {
			if(position >= 0 && position < mFragmentTitles.length){
				return mFragmentTitles[position];
			}
			return "";
		}
    }
    
    /**
     * @param newConfig Configuration
     */
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        MyLogger.logD(CLASS_TAG, "onConfigurationChanged");
        //getActionBar().getTabAt(0).setText(R.string.backup);
        //getActionBar().getTabAt(1).setText(R.string.restore);
        MyLogger.logD(CLASS_TAG, "onConfigurationChanged");
    }

    protected Dialog onCreateDialog(int id, Bundle args) {

        MyLogger.logI(CLASS_TAG, "oncreateDialog, id = " + id);
        switch (id) {
      //rlk delete meng.wu WSHBLL-1229 20160413 (start)
//            case DialogID.DLG_DELETE_AND_WAIT: {
//                ProgressDialog dialog = new ProgressDialog(this);
//                dialog.setCancelable(false);
//                dialog.setMessage(getString(R.string.delete_please_wait));
//                dialog.setIndeterminate(true);
//                return dialog;
//            }
            //rlk delete meng.wu WSHBLL-1229 20160413 (end)

            case DialogID.DLG_LOADING: {
                ProgressDialog dialog = new ProgressDialog(this);
                dialog.setCancelable(false);
                dialog.setMessage(getString(R.string.loading_please_wait));
                dialog.setIndeterminate(true);
                return dialog;
            }
            case DialogID.DLG_NO_SDCARD: {
                return new AlertDialog.Builder(this)
                        .setTitle(R.string.notice)
                        .setMessage(SDCardUtils.getSDStatueMessage(this))
                        .setCancelable(false)
                        .setPositiveButton(android.R.string.ok, new OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                MainActivity.this.finish();
                            }
                        }).create();
            }
            default: {
                MyLogger.logI(CLASS_TAG, "oncreateDialog, default");
            }
        }
        return null;
    }
    //A LBHBLW-567 by huan.yang 20160107 @{
    private void setSelectRestorePage(){
        if((getIntent().getIntExtra(Constants.KEY_TYPE,0))==NotifyManager.FP_NEW_DETECTION_NOTIFY_TYPE_LIST){
            mTabPager.setCurrentItem(1);
        }  
    }
    //@}
}
